# -*- coding: utf-8 -*-
import os
import re
import json
from PyQt5.QtWidgets import QFileDialog
from util.project_tree_maker import load_dir, show_dir, pickup_note_map
from ui_base import Ui_Dialog

class DirShowUI(Ui_Dialog):

    def __init__(self) -> None:
        super().__init__()
        self._vars['dir_show'] = '1.2.0.0'

    def dir_show_init(self):
        """
        绑定卡片内事件响应
        """
        self.dir_show_lineEdit_dirpath.setText(self.C.get('dir_show', 'dirpath', ''))
        self.dir_show_lineEdit_note_mark.setText(self.C.get('dir_show', 'note_mark', '#'))
        self.dir_show_lineEdit_exclude_names.setText(self.C.get('dir_show', 'exclude_names', ''))
        try:
            info = json.loads(self.C.get('dir_show', 'text_old', '{}')).get('info', '')
        except:
            info = ''
        self.dir_show_textEdit_text_old.setPlainText(info)
        self.dir_show_button_read_dir.clicked.connect(self.dir_show_button_read_dir_down)
        self.dir_show_button_run.clicked.connect(self.dir_show_button_run_down)


    def dir_show_button_read_dir_down(self):
        """选择目录按钮"""
        _path = self.dir_show_lineEdit_dirpath.text().strip()
        if _path and os.path.isdir(_path):
            _dir = _path
        else:
            _dir = os.getcwd()
        path = QFileDialog.getExistingDirectory(parent=self.widget, caption='目录', 
                                                      directory=_dir,
                                                     )
        if not path:
            return
        self.dir_show_lineEdit_dirpath.setText(path)
    
    def dir_show_button_run_down(self):
        """生成目录树"""
        #目录
        dir_path = self.dir_show_lineEdit_dirpath.text().strip()
        #排除名称
        exclude_names = self.dir_show_lineEdit_exclude_names.text().strip().split(';')
        #概要
        old_text = self.dir_show_textEdit_text_old.toPlainText().strip()
        #备注分隔符
        note_mark = self.dir_show_lineEdit_note_mark.text().strip()
        #config
        self.C.set('dir_show', 'dirpath', self.dir_show_lineEdit_dirpath.text())
        self.C.set('dir_show', 'note_mark', self.dir_show_lineEdit_note_mark.text())
        self.C.set('dir_show', 'exclude_names', self.dir_show_lineEdit_exclude_names.text())
        _info = self.dir_show_textEdit_text_old.toPlainText()
        self.C.set('dir_show', 'text_old', json.dumps({'info': _info}))
        self.C.save()
        #logic
        _map = pickup_note_map(old_text, note_mark, ex_pro=True)
        dir_map = load_dir(dir_path, _map, exclude_names, ex_pro=True)
        dir_map_res = show_dir(dir_map, note_mark, ex_pro=True)
        self.dir_show_textEdit_text_new.setText('\n'.join(dir_map_res))
        return True